package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 * 第二个Handler方法5\\
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		CreateOrderContext createOrderContext= (CreateOrderContext) context;
		List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();

//		List<Long> buyProductIds = createOrderContext.getBuyProductIds();
		List<Long> buyProductIds = new ArrayList<>();
		//在productId里面赋值
		if (CollectionUtils.isEmpty(buyProductIds)) {
			for (CartProductDto cartProductDto : cartProductDtoList) {
				buyProductIds.add(cartProductDto.getProductId());
			}
		}
		buyProductIds.sort(Long::compareTo);
		//锁定库存
		List<Stock> stocks = null;
		try {
			stocks = stockMapper.findStocksForUpdate(buyProductIds);
		} catch (Exception e) {
			throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
		}
		if (CollectionUtils.isEmpty(stocks)) {
			throw new BizException(OrderRetCode.STOCK_NOT_INIT.getCode(),OrderRetCode.STOCK_NOT_INIT.getMessage());
		}
		if (stocks.size() != buyProductIds.size()) {
			throw new BizException(OrderRetCode.STOCK_NOT_INIT_PART.getCode(),OrderRetCode.STOCK_NOT_INIT_PART.getMessage());
		}
		Integer restrictCount = stocks.get(0).getRestrictCount();
		//扣减库存
		for (CartProductDto cartProductDto : cartProductDtoList) {
			Long productId = cartProductDto.getProductId();
			Long productNum = cartProductDto.getProductNum();
			if (productNum.intValue() > restrictCount) {
				throw new BizException("0050100","该商品:"+cartProductDto.getProductName()+",超过限购数量,你的限购数量为:"+restrictCount);
			}
			Stock stock = new Stock();
			stock.setItemId(productId);
			stock.setLockCount(productNum.intValue());
			stock.setStockCount(-productNum);
			//修改库存信息
			stockMapper.updateStock(stock);
		}
		return true;
	}
}